package com.baizhi.controller;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.entity.Gurn;
import com.baizhi.service.GurnService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("gurn")
@Slf4j
public class GurnController {
    @Autowired
    private GurnService gurnService;
    @Value("${mypath}")
    private String path;
    @RequestMapping("selectAll")
    @ResponseBody
    @LogAnnotation(content="查询全部上师",type="查询")
    public Map selectAll(Integer page,Integer limit,String guruName){
        Map map = new HashMap();
        PageInfo<Gurn> pageInfo = gurnService.selectAll(page, limit, guruName);
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
    @RequestMapping("upload")
    @ResponseBody
    @LogAnnotation(content="文件上传",type="添加")
    public Map upload(MultipartFile file)throws Exception{
        String newName = UUID.randomUUID().toString() + file.getOriginalFilename();
        log.info("上师头像名字-------"+newName);
        file.transferTo(new File(path,newName));
        Map map = new HashMap();
        map.put("newName",newName);
        return map;
    }
    @RequestMapping("uploadXml")
    @ResponseBody
    @LogAnnotation(content="POI导入",type="导入")
    public Map uploadXml(MultipartFile file,Gurn gurn)throws Exception{
        InputStream inputStream = file.getInputStream();
        HSSFWorkbook sheets = new HSSFWorkbook(inputStream);
        HSSFSheet sheet = sheets.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <=lastRowNum; i++) {
            HSSFRow row = sheet.getRow(i);
            String name = row.getCell(1).getStringCellValue();
            String img = row.getCell(2).getStringCellValue();
            String niname = row.getCell(3).getStringCellValue();
            String status = row.getCell(4).getStringCellValue();
            int i1 = Integer.parseInt(status);
            // 封装到对象中
            gurn.setGuruName(name);
            gurn.setGuruImage(img);
            gurn.setGuruNickName(niname);
            gurn.setGuruStatus(i1);
            System.out.println(gurn);
            gurnService.insert(gurn);
        }
            Map map = new HashMap();
        map.put("flag",true);
        return map;
    }
    @RequestMapping("download")
    @ResponseBody
    @LogAnnotation(content="POI导出",type="导出")
    public Map download(HttpServletResponse response)throws Exception{
        response.setHeader("content-disposition",
                "attachment;filename="+ URLEncoder.encode("b.xls","UTF-8"));
        response.setContentType("application/vnd.ms-execl");
        Map map=new HashMap();
        try {
            String[] titles = {"上师编号","上师名字","上师图⽚地址","上师法号","上师状态"};
            //创建文件对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建xls表
            HSSFSheet sheet = workbook.createSheet("guru");
            //行数，从0开始
            HSSFRow titleRow = sheet.createRow(0);
            //列数，从0开始
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = titleRow.createCell(i);
                cell.setCellValue(titles[i]);

            }
            List<Gurn> gurns = gurnService.showAll(null);
            for (int i = 0; i < gurns.size(); i++) {
                HSSFRow row = sheet.createRow(i+1);
                // 将上师数据写⼊到⾏中
                Gurn gurn = gurns.get(i);
                //获取类对象
                Class<? extends Gurn> gurnClass = gurn.getClass();
                //获取属性
                Field[] fields = gurnClass.getDeclaredFields();

                for (int j = 0; j < fields.length; j++) {
                    //创建单元格
                    HSSFCell cell = row.createCell(j);
                    // 获取属性对象对应的属性值
                    Field field = fields[j];
                    field.setAccessible(true);
                    Object value = field.get(gurn);
                    // 将属性值写⼊到单元格 写出的时候⽤的全部都是String 那么读取的时候能够 getNumericCellValue() 吗？
                    cell.setCellValue(value.toString());
                }
            }
            map.put("flag",true);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            map.put("flag",false);
            e.printStackTrace();
        }
        System.out.println(map);
        return map;
    }
    @RequestMapping("addGurn")
    @ResponseBody
    @LogAnnotation(content="添加上师",type="添加")
    public Map addGurn(Gurn gurn){
        Map map = new HashMap();
        try {
            gurnService.insert(gurn);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
            e.printStackTrace();
        }
        return map;
    }
    @RequestMapping("updateGurn")
    @ResponseBody
    @LogAnnotation(content="更新上师",type="更新")
    public Map updateGurn(Integer guruStatus,Integer guruId){
        Map map = new HashMap();
        try {
            gurnService.update(guruStatus,guruId);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
            e.printStackTrace();
        }
        return map;
    }

}
